﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IotWeek2Day9.EFCore
{
    public class BaseRepository<T> : IRepository<T> where T : class
    {

        private readonly EmpDbContext _db;

        public BaseRepository(EmpDbContext db)
        {
            this._db = db;  //依赖注入
        }

        public int Add(T model)
        {
            try
            {
                _db.Set<T>().Add(model);
                return _db.SaveChanges();
            }
            catch (Exception)
            {

                throw;
            }

        }

        public int Delete(dynamic id) //dynamic动态类型
        {
            try
            {
                T model = _db.Set<T>().Find(id);
                _db.Set<T>().Remove(model);
                return _db.SaveChanges();
            }
            catch (Exception)
            {

                throw;
            }

        }

        public IQueryable<T> GetAll()
        {
            //return _db.Set<T>().ToList();  //在EF当中，ToList的作用是执行SQL语句并转换成List集合
            //数据的延迟加载
            return _db.Set<T>().AsQueryable();  //此处返回IQueryable<T>，可查询接口相当于一句SQL语句，
        }

        public T GetById(int id)
        {
            return _db.Set<T>().Find(id);
        }

        public int Update(T model)
        {
            try
            {
                _db.Set<T>().Update(model);
                return _db.SaveChanges();
            }
            catch (Exception)
            {

                throw;
            }

        }
    }
}
